package com.ttbj.product.api.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aliyuncs.exceptions.ClientException;
import com.ttbj.core.constants.SmsEnum;
import com.ttbj.core.dao.redis.IRedisStringBaseDao;
import com.ttbj.core.util.DtoTransitionUtils;
import com.ttbj.core.util.SendSMSUtil;
import com.ttbj.core.util.StringUtil;
import com.ttbj.exception.WebException;
import com.ttbj.product.api.AppletUserFacade;
import com.ttbj.product.bean.dto.UserDto;
import com.ttbj.user.bean.po.User;
import com.ttbj.user.dao.UserMapper;
import com.ttbj.util.Assert;
import com.ttbj.util.ResultUtil;

 


@Service("appletUserFacade")
public class AppletUserFacadeImpl  implements AppletUserFacade{
	
	@Autowired
	private UserMapper userMapper = null;
	@Autowired
	private IRedisStringBaseDao redisStringBaseDao = null;
	private Logger logger = LoggerFactory.getLogger(AppletUserFacadeImpl.class);
	

	
	@Override
	public void addUser(UserDto userDto) throws WebException {
		Assert.assertNonNullObj(userDto, 900, "添加用户信息为空,用户信息");
		User user =  (User)DtoTransitionUtils.trans(User.class, userDto);
		if(0 >= userMapper.insertSelective(user)){
			ResultUtil.throwExcepion(ResultUtil.createFail("messages", 900), "添加wx用户数据时失败:原因:添加失败");
		}
	}

	@Override
	public UserDto getUser(UserDto userDto) throws WebException {
		Assert.assertNonNullObj(userDto, 900, "获取用户信息参数为空，信息参数");
		User user = (User)DtoTransitionUtils.trans(User.class, userDto);
		return userMapper.getUser(user);
	}

	@Override
	public void updateUser(UserDto userDto) throws Exception {
		Assert.assertNonNullObj(userDto, 900, "修改用户信息参数为空，信息参数");
		User user = (User)DtoTransitionUtils.trans(User.class,userDto);
		if(0 >= userMapper.updateUser(user)){
			ResultUtil.throwExcepion(ResultUtil.createFail("messages", 900), "修改wx用户数据时失败:原因:插入失败");
		}
	}

 

	@Override
	public boolean verifySms(String phone, String code) throws Exception {
		if(StringUtil.isEmpty(phone)){
			return false;
		}
		String codeOrg = redisStringBaseDao.get(phone);
		if( StringUtil.isEmpty(code) || !code.equals(codeOrg)){
			return false;
		}
		return true;
	}

	@Override
	public void getSms(String phone)  {
		try {
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < 6; i++) {
				int codeEle = (int) Math.floor(Math.random() * 10);
				sb.append(codeEle + "");
			}
			String sms = sb.toString();
			redisStringBaseDao.set(phone, sms);
			SendSMSUtil.send(phone, "{\"code\":\"" + sms + "\"}", SmsEnum.SIGNNAME.getValue(), SmsEnum.TEMPLATECODE.getValue());
		} catch (ClientException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
	}

	 

}
